import { useSelector, useDispatch } from 'react-redux'
import { updateAllTodo } from '../store/actions/todo'
import TodoItem from './TodoItem'

export default function TodoMain() {
  const dispatch = useDispatch()
  const allTodo = useSelector((state) => state.todo)
  const todo = useSelector((state) => {
    // 根据另一个模块中的 active，返回对应的数据
    const active = state.filter.active
    if (active === 'Active') {
      return state.todo.filter((item) => !item.done)
    }
    if (active === 'Completed') {
      return state.todo.filter((item) => item.done)
    }
    return state.todo
  })
  const handleChangeAll = (done) => dispatch(updateAllTodo(done))
  // !先确定全选的状态
  const isCheckedAll = allTodo.every((item) => item.done)
  return (
    <section className='main'>
      <input
        id='toggle-all'
        className='toggle-all'
        type='checkbox'
        checked={isCheckedAll}
        onChange={() => handleChangeAll(!isCheckedAll)}
      />
      <label htmlFor='toggle-all'>Mark all as complete</label>
      <ul className='todo-list'>
        {todo.map((item) => (
          <TodoItem key={item.id} item={item} />
        ))}
      </ul>
    </section>
  )
}
